package com.hmdp.utils;

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;

@Component
public class RedisIdWorker {
    long BEGIN_TIMESTAMP = LocalDateTime.of(2003,8,1,0,0,0).toEpochSecond(ZoneOffset.UTC);
    StringRedisTemplate stringRedisTemplate;
    public RedisIdWorker(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    public long nextId(String keyPrefix) {
        //1.生成时间戳
        long nowSeconds = LocalDateTime.now().toEpochSecond(ZoneOffset.UTC);
        long timestamp = nowSeconds - BEGIN_TIMESTAMP;
        String dateToday = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));
        //2.生成序列号
        String idKey = "icr:"+keyPrefix+":"+dateToday;
        long count = stringRedisTemplate.opsForValue().increment(idKey);
        //3.拼接ID
        long id = timestamp<<32|count;
        return id;
    }
}
